<!-- 编辑管理员 -->

<template>
  <div class="main-context">
    <t-form style="width:600px" :rules="rules" ref="form" :data="formData" :disabled="isLook" @submit="onSubmit">
      <t-form-item label="用户名" name="name">
        <t-input v-model="formData.name" placeholder="请输入用户名" />
      </t-form-item>
      <t-form-item label="账号" name="account">
        <t-input v-model="formData.account" placeholder="请输入账号" />
      </t-form-item>
      <t-form-item label="密码" name="password">
        <t-input v-model="formData.password" placeholder="请输入账号" type="password" />
      </t-form-item>
      <t-form-item label="用户角色" name="roleId" class="role-item">
        <t-select
          v-model="formData.roleId"
          placeholder="-请选择-"
          :options="roleOptions"
          filterable
        />
      </t-form-item>
      <t-form-item label="备注" name="desc">
        <t-input v-model="formData.desc" placeholder=""/>
      </t-form-item>
      <t-form-item>
        <t-button theme="primary" type="submit" :disabled="disabled">确定</t-button>
      </t-form-item>
    </t-form>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { getRoleList } from '@/api/role'
import { managerAdd, getManagerInfo, managerUpdate } from '@/api/manager'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const { id, isLook } = route.query
const router = useRouter()
const formData = ref({})
const roleOptions = ref([])
const disabled = ref(false)
const rules = {
  name: [{ required: true }],
  account: [{ required: true }],
  password: [{ required: true }],
  roleId: [{ required: true }]
}
const onSubmit = ({ validateResult }) => {
  if (validateResult === true) {
    disabled.value = true
    const send = id ? managerUpdate : managerAdd
    send(formData.value).then(res => {
      const tip = DialogPlugin({
        theme: 'success',
        header: '操作成功',
        body: '是否返回列表页面',
        confirmBtn: '返回',
        onConfirm () {
          tip.hide()
          router.back()
        },
        onClose () {
          tip.hide()
        }
      })
    }).catch(err => {
      MessagePlugin.error({
        content: err.msg,
        duration: 2000
      })
    }).finally(() => {
      disabled.value = false
    })
  }
  console.log(formData.value)
}
// 获取角色列表以供选择
getRoleList().then(res => {
  res.data.forEach(item => {
    roleOptions.value.push({ label: item.name, value: item.id })
  })
})

if (id) {
  getManagerInfo({ id }).then(res => {
    formData.value = res.data
  })
}
</script>
<style scoped>
</style>
